package com.example.paymentdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.paymentdemo.entity.OrderInfo;
import com.example.paymentdemo.entity.Product;
import com.example.paymentdemo.enums.OrderStatus;
import com.example.paymentdemo.mapper.OrderInfoMapper;
import com.example.paymentdemo.mapper.ProductMapper;
import com.example.paymentdemo.service.OrderInfoService;
import com.example.paymentdemo.util.OrderNoUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author 上号
 * @Date 2022/5/14 10:42
 * @Version 1.0
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    @Resource
    private ProductMapper productMapper;

    @Override
    public OrderInfo createOrderByProductId(Long productId) {
        // 查询是否有记录
        OrderInfo orderInfo= getNoPayOrderByProductId(productId);
        if( orderInfo != null){
            return orderInfo;
        }

        //查找商品名称和价格
        Product product = productMapper.selectById(productId);
        //生成订单
         orderInfo = new OrderInfo();
        orderInfo.setTitle(product.getTitle());
        orderInfo.setOrderNo(OrderNoUtils.getOrderNo()); //订单号
        orderInfo.setProductId(productId);
        orderInfo.setTotalFee(product.getPrice()); //分
        orderInfo.setOrderStatus(OrderStatus.NOTPAY.getType());
        baseMapper.insert(orderInfo);
        return orderInfo;
    }

    /**
     * 存储二维码
     * @param orderNo  商户订单编号
     * @param codeUrl  二维码
     */
    @Override
    public void saveCodeUrl(String orderNo, String codeUrl) {
        // 构建条件
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        // 赋值
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCodeUrl(codeUrl);
        baseMapper.update(orderInfo,wrapper);
    }

    /**
     * 查询订单
     * @return
     */
    @Override
    public List<OrderInfo> listOrderByCreateTimeDesc() {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<OrderInfo>().orderByDesc("create_time");
        return baseMapper.selectList(wrapper);
    }

    /**
     *  是否有记录
     * @param productId
     * @return
     */
    private OrderInfo getNoPayOrderByProductId(Long productId) {
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId);
        wrapper.eq("order_status", OrderStatus.NOTPAY.getType());
        // 做一个关于用户的验证
        OrderInfo orderInfo = baseMapper.selectOne(wrapper);
        return orderInfo;
    }
}
